package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
public class ProducerQuickStart {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.kafka的配置信息
        Properties properties = new Properties();
        //kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092");

        //消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.MAX_REQUEST_SIZE_CONFIG, 104857600);
        //消息压缩算法
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "gzip");
        //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,5);
        //重试间隔
        properties.put(ProducerConfig.RETRY_BACKOFF_MS_CONFIG, 10);
        //批次大小
        properties.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
        //批次等待时间
        properties.put(ProducerConfig.LINGER_MS_CONFIG, 1);



        //2.生产者对象
        KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);

        //封装发送的消息
        ProducerRecord<String,String> record = new ProducerRecord<String, String>("yc-topic","100001"," 陈慧萱是一只小狗");
        long start=System.currentTimeMillis();
//        3.发送消息(同步发送)
        RecordMetadata recordMetadata = producer.send(record).get();
        System.out.println(recordMetadata.offset());

//        //异步发送
//        producer.send(record, new Callback() {
//            @Override
//            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
//                if(e == null){
//                    System.out.println(recordMetadata.offset());
//                }else{
//                    e.printStackTrace();
//                }
//            }
//        });
        long end=System.currentTimeMillis();
        System.out.println(end-start+"ms");
        //4.关闭消息通道，必须关闭，否则消息发送不成功
        producer.close();
    }

}